# Read Data of Range and Ephemeris from COM

import re
from tkinter import filedialog
import os
# 一行数据解析


# 位置数据解析
def getGNGGA(data):
    hms = int(data[0])
    Lat = float(data[1])
    Lng = float(data[2])
    sst = int(data[3])
    nsa = int(data[4])
    hdop = float(data[5])
    alt = float(data[6])
    dh = float(data[7])

    return [hms,Lat,Lng,alt,dh,sst,nsa,hdop]

# Main CMD
init_dir = os.getcwd()
filename = filedialog.askopenfilename(initialdir=init_dir, title="Select files", filetypes=[('all text files', '.txt')])
fileGPS = "gnssPV.txt"      # 输出文件gnssPV.txt（可以直接导入matlab）
fobj = open(filename,"r")
fpv = open(fileGPS,"w")
noVel = 0       # 速度无效标志，没有速度则不单独输出位置信息

for line in fobj.readlines():
    head = line[0:2]
    if head=="#B":
        searchStr = re.findall( r'#BESTVELA,COM1,0,.*?\.0,FINE,.*?,(.*?)\.000,00000000,.*?,.*?;SOL_COMPUTED,.*?,.*?,.*?,(.*?),(.*?),(.*?),.*?\*.*?\n', line, re.S)
        if not searchStr:
            noVel = 1       # 速度无效
            continue
        else:
            noVel = 0       # 速度有效
        #              周秒                 水平速度            航向                天向速度
        inputStr = searchStr[0][0]+' '+searchStr[0][1]+' '+searchStr[0][2]+' '+searchStr[0][3]+' '
        fpv.write(inputStr)

    elif head=="$G":
        searchStr = re.findall( r'\$[A-Z]+,(.*?)\.00,(.*?),N,(.*?),E,(.*?),(.*?),(.*?),(.*?),M,(.*?),M,.*?,0000\*.*?\n', line, re.S)
        if not searchStr:
            continue
        if noVel == 1:      # 速度无效时也不输出位置信息
            noVel = 0
            continue
        GPSData = getGNGGA(searchStr[0])
        inputStr = str(GPSData[0])+' '+str(GPSData[1])+' '+str(GPSData[2])+' '+str(GPSData[3])+' '+str(GPSData[4])+' '+str(GPSData[5])+' '+str(GPSData[6])+' '+str(GPSData[7])
        fpv.write(inputStr)
        fpv.write("\n")
    else:
        print("error")

fobj.close()
fpv.close()


